package mylibrary.thread.threadpool;

/**
 *  Create file and return the result
 */
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolWithResultTest {

	public static void main(String[] args) throws Exception {
		
		ExecutorService service = Executors.newFixedThreadPool(5);
		
		CompletionService completionService = new ExecutorCompletionService(service);
		
		List allResult = new ArrayList();
		for(int i=1; i<=10; i++) {
			
			Callable call = new FixedThreadPoolWithResultTest.Command(i);
			completionService.submit(call);
		}
		
		service.shutdown();
		
		//result
		System.out.println(new Timestamp(System.currentTimeMillis()) + " result");
		int res = 0;
		for(int i=1; i<=10; i++) {
			List<String> s = (List<String>)completionService.take().get();
			int m = Integer.valueOf(s.get(0));
			res += m;
		}
		System.out.println(new Timestamp(System.currentTimeMillis()) + " " + res);
	}
	
	private static class Command implements Callable {
		
		private int i;
		public Command(int i) {
			this.i = i;
		}
		public List call() {

			try {
				System.out.println(new Timestamp(System.currentTimeMillis()) + " Thread - " + i + " started");
				
				String fileName = "d:\\Test\\" + i + ".txt";
				File file = new File(fileName);
				Writer writer = new FileWriter(fileName);
				
				//10M
				while(file.length()<1024*1000*10) {
					writer.write("This is the test file \n\r");
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			System.out.println(new Timestamp(System.currentTimeMillis()) + " Thread - " + i + " finished");
			List result = new ArrayList();
			result.add(String.valueOf(i));
			return result;
		}
	}
}
